package qywx

import (
	"gitee.com/littletow/qywx/services/apps"
	"gitee.com/littletow/qywx/services/callback"
	"gitee.com/littletow/qywx/services/contacts"

	"gitee.com/littletow/qywx/services/caches"
	"gitee.com/littletow/qywx/services/tokens"
)

const (
	MEMORY_CACHE = iota
	REDIS_CACHE
	MEMCACHE_CAHCE
)

// GetCallbackManager 获取回调管理，可以进行URL验证，消息加解密
func GetCallbackManager(receiver_id string, token string, encodingAESKey string) *callback.CallbackManager {
	manager := callback.NewCallbackManager(receiver_id, token, encodingAESKey)
	return manager
}

// Qywx 企业微信实例，包含企业微信token仓储
type Qywx struct {
	tokenStore *tokens.AccessTokenStore
}

// NewCache 返回一个缓存，默认返回内存缓存，目前支持三种，内存，memcache，redis
func NewCache(cacheType int, redisOpts caches.RedisOpts, memcacheServer ...string) caches.Caches {
	var cache caches.Caches
	switch cacheType {
	case MEMORY_CACHE:
		cache = caches.NewMemory()
	case REDIS_CACHE:
		cache = caches.NewRedis(&redisOpts)
	case MEMCACHE_CAHCE:
		cache = caches.NewMemcache(memcacheServer...)
	default:
		cache = caches.NewMemory()
	}
	return cache
}

// NewQywx 返回一个企业微信实例，可以创建通讯录管理、应用管理等，需要先创建一个缓存
func NewQywx(caches caches.Caches) *Qywx {
	tokenStore := tokens.NewAccessTokenStore(caches)
	return &Qywx{tokenStore: tokenStore}
}

// GetContactManager 获取通讯录管理实例，包含qywx全局配置，token仓库
func (qy *Qywx) GetContactManager(corpid string, agentid string, secret string) *contacts.ContactManager {
	manager := contacts.NewContactManager(corpid, agentid, secret, qy.tokenStore)
	return manager
}

// GetCustomAppManager 获取自建应用管理实例，包含qywx全局配置，token仓库
func (qy *Qywx) GetCustomAppManager(corpid string, agentid string, secret string) *apps.CustomAppManager {
	manager := apps.NewCustomAppManager(corpid, agentid, secret, qy.tokenStore)
	return manager
}
